<?php
/*
 *
 *      functions.php - v1.0.0 @07.07.2009 22:29:40 CEST
 *
 *      StudioGallery Copyright (C) 2009 Rafal Kusior (spuavick) <spuavick@interia.pl>
 *
 *      This program is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *      -----------------------------------------------------------------------------
 *
 *      Niniejszy program jest wolnym oprogramowaniem - możesz go rozpowszechniać
 *      dalej i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU
 *      wydanej przez Fundację Wolnego Oprogramowania, według wersji 2 tej Licencji
 *      lub dowolnej z późniejszych wersji.
 *
 *      Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on użyteczny -
 *      jednak BEZ ŻADNEJ GWARANCJI, nawet domyślnej gwarancji PRZYDATNOŚCI HANDLOWEJ
 *      albo PRZYDATNOŚCI DO OKREŚLONYCH ZASTOSOWAŃ. Bliższe informacje na ten temat
 *      można uzyskać z Powszechnej Licencji Publicznej GNU.
 *
 *      Kopia Powszechnej Licencji Publicznej GNU powinna zostać ci dostarczona
 *      razem z tym programem. Jeżeli nie została dostarczona, odwiedź
 *      <http://www.gnu.org/licenses/>
 */


/** pobranie konfiguracji z DB
 *
 * name: configDB
 * @param: none;
 * @return: array
 */

function configDB() {

	global $db;
	$r = $db->select("SELECT * FROM "._pre_."configuration;");
	$row = $db->get_row($r,'MYSQL_ASSOC');
	return $row;

}


/** aktualny adres strony
 *
 * name: urlPage
 * @param: none
 * @return: actual path
 */

function urlPage() {

	$path = explode("/",$_SERVER['REQUEST_URI']);
	array_pop($path);
	$path = implode("/",$path);
	$path = $_SERVER['HTTP_HOST'].$path;
	return $path;
}


/** przeksztalcenie daty na mikrotime
 *
 * name: mdata
 * @param: date ( Y-m-d H:i )
 * @return: mikrotime
 */

function mdata( $data ) {

	$rok = date("Y", strtotime($data));
	$miesiac = date("n", strtotime($data));
	$dzien = date("j", strtotime($data));
	$godzina = date("G", strtotime($data));
	$minuty = intval(date("i", strtotime($data)));
	$sekundy = intval(date("s", strtotime($data)));
	$mdata = mktime($godzina,$minuty,$sekundy,$miesiac,$dzien,$rok);

	return $mdata;

}


/** aktualna data
 *
 * name: datanow
 * @param: none
 * @return: date ( Y-m-d H:i )
 */

function datanow() {

	return date("Y-m-d H:i");

}


/** konwersja daty z formatu mikrotime
 *
 * name: mdate2date
 * @param: mikrotime
 * @return: date ( Y:m-d H:i )
 */

function mdate2date($data) {

	return date("Y-m-d H:i",$data);

}


/** sprawdzenie uprawnien zapisu
 *
 * name: checkPermission
 * @param: file or dir
 * @return: true or false;
 */

function checkPermission($what) {

	if (!$what) return false;

		if (is_writable($what)) {

		return true;

		} else {

		return false;

		}

}


/** pseudolosowa generacja ciagu znakow
 *
 * name: passGen
 * @param: (int)
 * @return: $key
 */

function passGen($length) {

	$pattern = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	$key  = $pattern{mt_rand(0,61)};
	$i=1;

	while($i<$length) {

		$key .= $pattern{mt_rand(0,61)};

		$i++;

	}

	return $key;

}


/** podkategorie z danej kategorii
 *
 * name: selectsubcat
 * @param: $id category
 * @return: array - all subcategories
 */

function selectsubcat( $id ) {

	global $db;
	$q = $db->select("SELECT * FROM "._pre_."category WHERE cat_sub_id = ".(int)$id." ORDER BY cat_id ASC;");

	while ($row = $db->get_row($q,'MYSQL_ASSOC')) {

		$tabela[] = $row;

	}

	return $tabela;

}


/** pobranie kategorii
 *
 * name: selectcat
 * @param: $id category
 * @return: category for $id
 */

function selectcat($id=false) {

	global $db;
	if (!$id) {

		$q = $db->select("SELECT * FROM "._pre_."category WHERE cat_sub_id = 0 ORDER BY cat_id ASC;");

		while ($row = $db->get_row($q,'MYSQL_ASSOC')) {

			$tabela[] = $row;

		}

	} else {

		$q = $db->select('SELECT * FROM '._pre_.'category WHERE cat_id = '.(int)$id.' ORDER BY cat_id ASC;');

		while ($rowek = $db->get_row($q,'MYSQL_ASSOC')) {

			$t=$db->select("SELECT * FROM "._pre_."category WHERE cat_id = ".$rowek['cat_sub_id']." AND cat_sub_id = 0 AND cat_show >0");

			while($roweczek = $db->get_row($t,'MYSQL_ASSOC')) {

				$tabela[] = $roweczek;

			}

			$tabela[] = $rowek;

		}

	}

	return $tabela;

}


/** rysowanie drzewka menu
 *
 * name: subsubcat
 * @param: $subcat - subcategory; $id - category
 * @return: menu;
 */

function subsubcat( $subcat,$id=false ) {

	global $db;
	if ($subcat) {

		$menu .= "<ul class=\"smenu\">\n";

		$j=0;
		while(isset($subcat[$j])) {

			if ($subcat[$j]['cat_id'] == $id) $current = ' class="current"'; else $current = '';

				$menu .= "<li><div><a".$current." href=\"gallery.php?cat=".$subcat[$j]['cat_id']."\">".$subcat[$j]['cat_name']." (".countPhotos($subcat[$j]['cat_id']).")</a></div>";
				$menu .= subsubcat(selectsubcat($subcat[$j]['cat_id']));

		$j++;
		}

		$menu .= "</ul>\n";
		$menu .= "</li>\n";

	} else {

		$menu .= "</li>\n";

	}

	return $menu;

}


/** początek rysowania menu
 *
 * name: subCatMenu
 * @param: $id
 * @return: menu
 */

function subCatMenu($id=false) {

	global $db;
	if (!$id) {

		$kategorie = selectcat(false);
		$menu .= "<ul class=\"smenu\">\n";

		$i=0;
		while(isset($kategorie[$i])) {

			$menu .= "<li><div><a href=\"gallery.php?cat=".$kategorie[$i]['cat_id']."\">".$kategorie[$i]['cat_name']." (".countPhotos($kategorie[$i]['cat_id']).")</a></div>\n";
			$subcat = selectsubcat($kategorie[$i]['cat_id']);
			$menu .= subsubcat($subcat,$id);

		$i++;
		}

		$menu .= "</ul>\n";

	} else {

		$menu .= "<ul class=\"smenu\">\n";
		$kategorie = selectcat($id);

		if ($kategorie[0]['cat_id'] == $id) $current = ' class="current"'; else $current = '';

		$menu .= "<li><div><a".$current." href=\"gallery.php?cat=".$kategorie[0]['cat_id']."\">".$kategorie[0]['cat_name']." (".countPhotos($kategorie[0]['cat_id']).")</a></div>\n";
		$subcat = selectsubcat($kategorie[0]['cat_id']);

		if ($subcat) {

			$menu .= subsubcat($subcat,$id);

		}

		$menu .="</ul>";

	}

	return $menu;

}


/** katalogi z motywem
 *
 * name: themeDir
 * @param: conf
 * @return: themes
 */

function themeDir($conf=false) {

	$calosc = array();
	$nadrzedny="../templates/";

	$kat=opendir($nadrzedny);
	$calosc="";

	$a = -1;
	while($katalogi=readdir($kat)) {

		if (($katalogi!=".")&&($katalogi!="..")&&(!is_file($nadrzedny.$katalogi))) {

			$a++;
			$dir[] = $katalogi;
			$calosc .= $katalogi.' | ';

		}


	}

	closedir($kat);
	sort($dir);

	$calosc = explode(' | ', $calosc);
	$ile = $a + 1;
	$form = '<select name="theme"> ';
	$form_end = '</select>';

	$i=0;
	while($i<$ile) {

		if ($conf == $dir[$i]) $selected = " selected=\"selected\""; else $selected = "";
		$select .= '<option value="'.$dir[$i].'"'.$selected.'>'.$dir[$i].'</option>';

	$i++;
	}

	$select = $form.$select.$form_end;

	return $select;
}


/** wybieranie kategorii
 *
 * name: selectCategories
 * @param: $conf
 * @return: categories option
 */

function selectCategories($conf=false) {

	global $db;
	$option = '';

	$q = $db->select("SELECT * FROM "._pre_."category ORDER BY cat_id ASC, cat_sub_id ASC;");

	while($caty = $db->get_row($q,'MYSQL_ASSOC')) {

		$cat[] = $caty;

	}

	if (count($cat)>0) {

		$i=0;
		while($i<count($cat)) {

			if ($conf == $cat[$i]['cat_id']) $select = ' selected="selected"'; else $select = '';

			$option .= "<option value=\"".$cat[$i]['cat_id']."\"".$select.">".$cat[$i]['cat_name']."</option>";

			$i++;
		}

		return $option;

	}

	return null;

}


/** przekształcenie linka w przypadku podkatalogu
 *
 * name: subCat
 * @param: $preU, $content
 * @return: $new_content
 */

function subCat ($preU,$content) {

  		$content = preg_replace("#<a(.*?)href=\"(.*?)\"#","<a$1href=\"".$preU."$2\"",$content);

	return $content;

}


/** utworzenie linków do edycji i usunięcia kategorii
 *
 * name: subCatEdit
 * @param: $content
 * @return: $new_content
 */

function subCatEdit($content) {

	$content = preg_replace("#cat=(.*?)\">(.*?)\s\([0-9]+\)</a>#","cat=$1\">$2</a><div class=\"redit\">(<a href=\"#\" onclick=\"delCat('$1'); return false;\">usuń</a> | <a href=\"#\" onclick=\"editCat('$1','$2'); return false;\">edytuj</a> )</div>",$content );

	return $content;

}


/** czyszczenie danych
 *
 * name: mysql_real_escape_array
 * @param: $_POST
 * @return: mysql_real_escape_string or stripslashes data from $_POST
 */

function mysql_real_escape_array($t){

	if (get_magic_quotes_gpc()) {

		$t = array_map("stripslashes", $t);

	}

	return array_map("mysql_real_escape_string",$t);

}


/** podostrzanie obrazu
 *
 * name: UnsharpMask
 * @param: $img - obrazek, $amout - jakosc, $radious - promien, $treshold - ostrzenie
 * @return: unsharp img
 */

function UnsharpMask($img, $amount, $radius, $threshold) {

	if ($amount > 500) $amount = 500;

	$amount = $amount * 0.016;

	if ($radius > 50) $radius = 50;

	$radius = $radius * 2;

	if ($threshold > 255) $threshold = 255;

	$radius = abs(round($radius));

	if ($radius == 0) {

		return $img;
		imagedestroy($img);
		break;

	}

	$w = imagesx($img);
	$h = imagesy($img);
	$imgCanvas = $img;
	$imgCanvas2 = $img;
	$imgBlur = imagecreatetruecolor($w, $h);

	for ($i = 0; $i < $radius; $i++) {

		imagecopy		($imgBlur, $imgCanvas, 0, 0, 1, 1, $w - 1, $h - 1); // up left
		imagecopymerge	($imgBlur, $imgCanvas, 1, 1, 0, 0, $w, $h, 50); // down right
		imagecopymerge	($imgBlur, $imgCanvas, 0, 1, 1, 0, $w - 1, $h, 33.33333); // down left
		imagecopymerge	($imgBlur, $imgCanvas, 1, 0, 0, 1, $w, $h - 1, 25); // up right
		imagecopymerge	($imgBlur, $imgCanvas, 0, 0, 1, 0, $w - 1, $h, 33.33333); // left
		imagecopymerge	($imgBlur, $imgCanvas, 1, 0, 0, 0, $w, $h, 25); // right
		imagecopymerge	($imgBlur, $imgCanvas, 0, 0, 0, 1, $w, $h - 1, 20 ); // up
		imagecopymerge	($imgBlur, $imgCanvas, 0, 1, 0, 0, $w, $h, 16.666667); // down
		imagecopymerge	($imgBlur, $imgCanvas, 0, 0, 0, 0, $w, $h, 50); // center

	}

	$imgCanvas = $imgBlur;

	for ($x = 0; $x < $w; $x++) {

		for ($y = 0; $y < $h; $y++) {

			$rgbOrig = ImageColorAt($imgCanvas2, $x, $y);
			$rOrig = (($rgbOrig >> 16) & 0xFF);
			$gOrig = (($rgbOrig >> 8) & 0xFF);
			$bOrig = ($rgbOrig & 0xFF);
			$rgbBlur = ImageColorAt($imgCanvas, $x, $y);
			$rBlur = (($rgbBlur >> 16) & 0xFF);
			$gBlur = (($rgbBlur >> 8) & 0xFF);
			$bBlur = ($rgbBlur & 0xFF);

			$rNew = (abs($rOrig - $rBlur) >= $threshold) ? max(0, min(255, ($amount * ($rOrig - $rBlur)) + $rOrig)) : $rOrig;
			$gNew = (abs($gOrig - $gBlur) >= $threshold) ? max(0, min(255, ($amount * ($gOrig - $gBlur)) + $gOrig)) : $gOrig;
			$bNew = (abs($bOrig - $bBlur) >= $threshold) ? max(0, min(255, ($amount * ($bOrig - $bBlur)) + $bOrig)) : $bOrig;

			if (($rOrig != $rNew) || ($gOrig != $gNew) || ($bOrig != $bNew)) {

				$pixCol = ImageColorAllocate($img, $rNew, $gNew, $bNew);
				ImageSetPixel($img, $x, $y, $pixCol);

			}

		}

	}

	return $img;
}


/** utworzenie miniaturki
 *
 * name: imageResize
 * @param: $file, $file_r, $w, $h
 * @return: new thumb
 */

function imageResize($file, $file_r, $w, $h) {

	$OldImage=ImageCreateFromJpeg($file);
	list($width,$height)=getimagesize($file);
	$_ratio=array($width/$height,$w/$h);

		if ($_ratio[0] != $_ratio[1]) { // crop

			$_scale=min((float)($width/$w),(float)($height/$h));
			$cropX=(float)($width-($_scale*$w));
			$cropY=(float)($height-($_scale*$h));
			$cropW=(float)($width-$cropX);
			$cropH=(float)($height-$cropY);

			$crop=ImageCreateTrueColor($cropW,$cropH);
            ImageCopy($crop,$OldImage,0,0,(int)($cropX/2),(int)($cropY/2),$cropW,$cropH);

		}

		$NewThumb=ImageCreateTrueColor($w,$h);

		if (isset($crop)) {

			ImageCopyResampled($NewThumb,$crop,0,0,0,0,$w,$h,$cropW,$cropH);
			ImageDestroy($crop);

		} else { // ratio

			ImageCopyResampled($NewThumb,$OldImage,0,0,0,0,$w,$h,$width,$height);

		}

		$NewThumb = UnsharpMask($NewThumb,80,.5,3);

		imagejpeg($NewThumb,$file_r,91);
		ImageDestroy($NewThumb);
		ImageDestroy($OldImage);
		chmod($file_r,0777);

}


/** odczytanie Exif
 *
 * name: readExif
 * @param: $file
 * @return: exif for DB
 */

function readExif($file) {

	require_once('../libs/exif/exif.php');

	$path = $file;
	$verbose =0;
	$result = read_exif_data_raw($path,$verbose);

	// $make = trim($result['IFD0']['Make']);
	$model = trim($result['IFD0']['Model']);
	$dataZD = trim($result['SubIFD']['DateTimeOriginal']);
	$czas = trim($result['SubIFD']['ExposureTime']);
	$przyslona = trim($result['SubIFD']['FNumber']);
	$ogniskowa = trim($result['SubIFD']['FocalLength']);

//	if (strlen($make) == 0) {

//		$ExifZ = "";

//	} else {

//		$ExifZ = $make;

//	}

	if (strlen($model) == 0) {

		$ExifZ .= "";

	} else {

		$ExifZ .= "$model &#8226;";

 	}

	if (strlen($przyslona) == 0) {

		$ExifZ .= "";

	} else {

		$ExifZ .= " $przyslona";

	}

	if (strlen($czas) == 0) {

		$ExifZ .= "";

	} else {

		$ExifZ .= " &#8226; $czas";

	}

	if (strlen($ogniskowa) == 0) {

		$ExifZ .= "";

	} else {

		$ExifZ .= " &#8226; $ogniskowa";

	}

	if (strlen($dataZD) == 0) {

		$ExifZ .= "";

	} else {

		//$ExifZ .= " &#8226; <em>$dataZD</em>";
	}

	if ($ExifZ == '') {

		$ExifZ = "";

	} else {

		$ExifZ = "$ExifZ";

	}

	$exifPh = $ExifZ;

	return $exifPh;

}


/** formularz edycji zdjęcia
 *
 * name: photoEditForm
 * @param: none
 * @return: form
 */

function photoEditForm() {

    global $db,$sghook;
    $r = $db->select("SELECT * FROM "._pre_."photo WHERE photo_cat_id = 0;");

	while($row = $db->get_row($r,'MYSQL_ASSOC')) {

		$photo[] = $row;

	}

	$i=0;

	if (count($photo)>0) {

		if ($photo[$i]['photo_show'] == 1) $check = " checked=\"checked\"";

		$form 	 = '<form id="photoedit" action="#" method="post" name="photoedit">';
		$form	.= '<div class="form">
						<div class="c">
							<img src="../photos/'.$photo[$i]['photo_file'].'_m.jpg" alt="" />
							<input type="hidden" name="id" id="id" value="'.$photo[$i]['photo_id'].'" />
						</div>
					</div>
					<div class="clr"></div>';
		$form 	.= '<div class="form">
						<div class="l"><label for="kategoria">';
		$form 	.= _("Kategoria zdjęcia:");
		$form 	.= '</label>
							<select name="kategoria" id="kategoria"><option value="0">--wybierz kategorię--</option>'.selectCategories($photo[$i]['photo_cat"id']).'</select>
						</div>
					</div>
					<div class="clr"></div>';
		$form 	.= '<div class="form">
						<div class="l"><label for="title">';
		$form 	.= _("Tytuł zdjęcia:");
		$form 	.= '	</label><input type="text" name="title" id="title"/></div></div><div class="clr"></div>';
		$form 	.= '<div class="form">
						<div class="l"><label for="desc">';
		$form 	.= _("Opis zdjęcia:");
		$form 	.= '		</label><textarea name="desc" id="desc"></textarea>
						</div>
					</div>
					<div class="clr"></div>';
		$form 	.= '<div class="form">
						<div class="l"><label for="public">';
		$form	.= _("Publikuj:");
		$form	.= '	</label>	<input type="checkbox" name="public" id="public" value="1"'.$check.' />
						</div>
					</div>
					<div class="clr"></div>';
		$form 	.= '<div class="form">
						<div class="l"><label for="delete">
							<strong>';
		$form	.= _("Usuń:");
		$form	.= '		</strong></label>
							<input type="checkbox" name="delete" id="delete" value="1" />
						</div>
					</div>
					<div class="clr"></div>';
		if ($sghook->hooks_exist('photo')) {
		    $form .= $sghook->execute_hooks('photo',$row);
		}
		$form 	.= '<div class="form">
						<div class="c">
							<input type="submit" name="submit" value="';$form .= _("aktualizuj"); $form .='" id="send_aktual_photo" class="button" />
						</div>
					</div>
					<div class="clr"></div>
					</form> ';

		} else {

			$form 	 = '<div class="ok">';
			$form	.= _("wszystkie zdjęcia zaktualizowano");
			$form	.= '</div>';

		}

	return $form;

}


/** stronnicowanie wyników dla Ajaxa
 *
 * name: pagArrayJS
 * @param: $array, $page, $limit, $function
 * @return: array($results+$pages)
 */

function pagArrayJS($array, $page=0, $limit=10, $function="pagine") {

	if (count($array) > 0 ) {

		$pag = ceil(count($array) / $limit);

		if ($page>1) $pages[] = "<a href=\"#\" onclick=\"".$function."('1'); return false;\">&laquo;&laquo;</a>";

		$pa = $page-1;

		if ($pa>=1) $pages[] = "<a href=\"#\" onclick=\"".$function."('".$pa."'); return false;\">&laquo;</a>";

		$i=1;
		while($i<$pag+1) {

			if ($page<1 && $i==1 || $page == $i) {

				$pages[] = '<span class="nr">'.$i.'</span>';

			} else {

				$pages[] = "<a href=\"#\" onclick=\"".$function."('".$i."'); return false;\">".$i."</a>";

				$pp[] = $i;
				$s1 = $i+1;

				if ($page >= 1 ) $p = $page + 1; else $p = $page + 2;

				if ($s1 == $pag+1 ) $pages[] = "<a href=\"#\" onclick=\"".$function."('".$p."');return false;\">&raquo;</a>";

			}

			$i++;
		}

		if ($page<$pag && $pag>1)

			 $pages[] = "<a href=\"#\" onclick=\"".$function."('".array_pop($pp)."');return false;\">&raquo;&raquo;</a>";

		if ($page<1) $page = 1;

			$end = $limit * $page;

		$start = ($page - 1) * $limit;

		$i=$start;
		while($i<$end) {

			if (isset($array[$i])) {

				$narray[] = $array[$i];

			}

			$i++;
		}

		if (count($pages)>1) {

			return array($narray,$pages);

		} else {

			return array($narray,false);

		}

	} else {

		return false;

	}
}


/** link dl Lightbox'a lub nie
 *
 * name: jQueryLightbox
 * @param: $text, $file, $title, $what
 * @return: $rel
 */

function jQueryLightbox($text,$file,$title,$what) {

	global $db;
	$conf = configDB();

		if ($conf['conf_jquery_lightbox'] == 1) {

			$rel = '<a rel="lightbox[\''.$text.'\']" href="photos/'.$file.'.jpg" title="'.$title.'">'.$what.'</a>';

			return $rel;

		} if ($conf['conf_jquery_lightbox'] == 2) {

			$rel = '<a rel="group" href="photos/'.$file.'.jpg" title="'.$title.'">'.$what.'</a>';

			return $rel;

		} else {

			$rel = '<a href="photo.php?f='.$file.'">'.$what.'</a>';

			return $rel;

		}
}


/** ostatnie trzy zdjęcia
 *
 * name: lastPhoto
 * @param: none
 * @return: the last 3 img
 */

function lastPhoto() {
	global $db;

	$r = $db->select("SELECT * FROM "._pre_."photo WHERE photo_show>0 ORDER BY photo_date DESC;");

	while($row = $db->get_row($r,'MYSQL_ASSOC')) {

		$photo[] = $row;

	}

	if (count($photo)>=3) $max = 3; else $max = count($photo);

	$i=0; $lista = '';
	$title = '<h2>'._("Ostatnie zdjęcia").'</h2>';
	$start_tag = '<ul class="lastphoto">'; $end_tag = '</ul>';
	while($i<$max) {

		$lastphoto[$i] = $photo[$i];
		$lastphoto[$i]['img'] = jQueryLightbox("preview",$photo[$i]['photo_file'],$photo[$i]['photo_title'],'<img src="photos/'.$photo[$i]['photo_file'].'_s.jpg" alt="'.$photo[$i]['photo_title'].'" />');
		$lista .= "<li>".$lastphoto[$i]['img']."</li>\n";
		$i++;
	}
	$lista = $title.$start_tag.$lista.$end_tag;
	return $lista;

}


/** ostatnich pięć wpisów
 *
 * name: lastnews
 * @param: none
 * @return: the last 5 news
 */

function lastnews(){
	global $db;

		$r = $db->select("SELECT * FROM "._pre_."blog WHERE news_show > 0 ORDER BY news_id DESC;");

		while($row = $db->get_row($r,'MYSQL_ASSOC')) {

			$news[] = $row;

		}

		if (count($news)>=5) $max = 5; else $max = count($news);

		$i=0; $lista = '';
		$title = '<h2>'._("Ostatnie wpisy").'</h2>';
		$start_tag = '<ul class="list">'; $end_tag = '</ul>';
		while($i<$max) {

			$lastnews[$i] = $news[$i];
			$lastnews[$i]['date'] = date("d-m-Y",$news[$i]['news_date']);
			$lastnews[$i]['link'] = '<a href="news.php?id='.$news[$i]['news_id'].'" title="'.$news[$i]['news_title'].'-'.$lastnews[$i]['date'].'">'.$news[$i]['news_title'].'</a>';
			$lista .= "<li>".$lastnews[$i]['link']."</li>\n";
			$i++;
		}
		$lista = $title.$start_tag.$lista.$end_tag;

	return $lista;

}


/** dodanie &raquo; do linków
 *
 * name: raquoMenu
 * @param: $cont
 * @return: $links
 */

function raquoMenu($cont) {
	global $db;

	preg_match_all('#<div>(.*?)<\/div>#', $cont, $matches);

	$i=0;
	$linki='';

	while($i<count($matches[1])) {

		if ($i+1 == count($matches[1])) $more = ' '; else $more = ' &raquo; ';

		$linki  .= linkuj($matches[1][$i],$conf['conf_url']).$more;

		$i++;
	}

	return $linki;

}


/** linkowanie
 *
 * name: linkuj
 * @param: $content, $url, $format
 * @return: $content
 */

function linkuj($content,$url,$format=false) {

	$content = preg_replace("#<a(.*?)href=\"(.*?)\"#","<a$1href=\"".$url."$2\"",$content);

	return $content;

}


/** utworzenie górnego menu
 *
 * name: menu
 * @param: none
 * @return: menu
 */

function menu() {
	global $db;

	$r = $db->select("SELECT * FROM "._pre_."configuration");
	$conf = $db->get_row($r,'MYSQL_ASSOC');

	if ($conf['conf_page'] !=0 && $conf['conf_start_page'] != 1) {

		$q = $db->select("SELECT * FROM "._pre_."page");
		while ($row = $db->get_row($q,'MYSQL_ASSOC')) {

		    $special = '<li><a href="page.php?page='.sg_url_clear($row['page_title']).'">'.$row['page_title'].'</a></li>';

		}

	} else {

		$special = '';
	}
	if ($conf['conf_blog'] !=0 && $conf['conf_start_page'] != 0) {

		$blog = '<li><a href="news.php">'.$conf['conf_blog_title'].'</a></li>';

	} else {

		$blog = '';
	}
	$menu = '<ul id="nav" class="clearfix"><li><a href="'.$conf['conf_url'].'">';
	$menu .=_("strona główna");
	$menu .='</a></li>'.$blog.'<li><a href="gallery.php">';
	$menu .= _("galeria");
	$menu .='</a>'.subCatMenu(false).'</li>'.$special.'</ul>';

	return $menu;


}

/** zliczanie zdjęć w kategorii
 *
 * name: countPhotos
 * @param: $catid
 * @return: $il
 */

function countPhotos($catid,$subcat=false) {
	global $db;

	$il = 0;
	//   $t = $db->select("SELECT * FROM "._pre_."category WHERE cat_id = ".$catid." OR cat_sub_id = ".$catid);
	//   while($tow = $db->get_row($t,'MYSQL_ASSOC')){						$tow['cat_id']

	$r=$db ->select("SELECT COUNT(photo_cat_id) as photo_ile FROM "._pre_."photo WHERE photo_cat_id = ".$catid." AND photo_show > 0;");
	$ile = $db->get_row($r,'MYSQL_ASSOC');

	$il += $ile['photo_ile'];
	if ( $subcat ) {
		$more = getSubCat($catid);
		if ( is_array($more) ) {
			$i=0;
			while($i<count($more)) {
				$m = $db->select("SELECT COUNT(photo_cat_id) as photo_ile FROM "._pre_."photo WHERE photo_cat_id = ".$more[$i]['cat_id']." AND photo_show > 0;");
				$ile = $db->get_row($m,'MYSQL_ASSOC');
				$il += $ile['photo_ile'];
				$i++;
			}
		}
	}
	//   }

return $il;

}


/** pobieranie IP użytkownika
 *
 * name: showIP
 * @param: none
 * @return: IP
 */

function showIP() {

	if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))

		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];

	else
		$ip = $_SERVER["REMOTE_ADDR"];

	return $ip;

}

function sg_url_clear($sText) {
	$aReplacePL = array(
		'ą' => 'a', 'ę' => 'e', 'ś' => 's', 'ć' => 'c',
		'ó' => 'o', 'ń' => 'n', 'ż' => 'z', 'ź' => 'z', 'ł' => 'l',
		'Ą' => 'A', 'Ę' => 'E', 'Ś' => 'S', 'Ć' => 'C',
		'Ó' => 'O', 'Ń' => 'N', 'Ż' => 'Z', 'Ź' => 'Z', 'Ł' => 'L',
		'Š' => 'S');

	return str_replace(array_keys($aReplacePL), array_values($aReplacePL), $sText);
}

function sg_url($sText) {
	$sText = sg_url_clear($sText);
	$sText = strtolower($sText);
	$sText = str_replace(' ', '-', $sText);
	$sText = preg_replace('/[^0-9a-z\-]+/', '', $sText);
	$sText = preg_replace('/[-]+/', '-', $sText);
	$sText = trim($sText, '-');

	return $sText;
}


/** komentarze wg id wiadomosci
 *
 * name: commentsByIdNews
 * @param: $id
 * @return: array(comments+sum)
 */
function commentsByIdNews($id) {
	global $db;

	$r = $db->select("SELECT * FROM "._pre_."comments WHERE com_news_id = ".$id);

	while($row = $db->get_row($r,'MYSQL_ASSOC')) {

		$comments[] = $row;

	}

	$ile = count($comments);

	return array($comments,$ile);

}


/** komentarze wg $id zdjęcia
 *
 * name: commentsByIdPhoto
 * @param: $id
 * @return: array(comments+sum)
 */

function commentsByIdPhoto($id) {
	global $db;

	$r = $db->select("SELECT * FROM "._pre_."comments WHERE com_photo_id = ".$id);

	while($row = $db->get_row($r,'MYSQL_ASSOC')) {

		$comments[] = $row;

	}

	$ile = count($comments);

	return array($comments,$ile);

}


/** podmiana dany na różne formaty
 *
 * name: dataPublic
 * @param: $d, $j
 * @return: changed date
 */

function dataPublic($d, $j) {

	$d = strtotime($d);
	$dTyg = array (
					"0"=>_("niedziela"),
					"1"=>_("poniedziałek"),
					"2"=>_("wtorek"),
					"3"=>_("środa"),
					"4"=>_("czwartek"),
					"5"=>_("piątek"),
					"6"=>_("sobota"),
				);
	$m = array(
					"0" => "",
					"1"=>_("stycznia"),
					"2"=>_("lutego"),
					"3"=>_("marca"),
					"4"=>_("kwietnia"),
					"5"=>_("maja"),
					"6"=>_("czerwca"),
					"7"=>_("lipca"),
					"8"=>_("sierpnia"),
					"9"=>_("września"),
					"10"=>_("października"),
					"11"=>_("listopada"),
					"12"=>_("grudnia")
			);

	if ( $j == 1 ) {

		$dT = $dTyg[date("w", $d)];

	} else if ( $j == 2 ) {

		$mD = $m[date("n", $d)];
		$dD = $dTyg[date("w", $d)].", ".date("d", $d)." ".$mD." ".date(" (G:i)", $d);

	} else if ( $j == 3 ) {

		$dD = $dTyg[date("w", $d)].", ".date("j m Y (G:i)", $d);

	} else if ( $j == 4 ) {

		$mD = $m[date("n", $d)];
		$dD = date("d", $d)." ".$mD.date(" (G:i)", $d);

	} else if ( $j == 5 ) {

		$dD = $dTyg[date("w", $d)].", ".date("j ", $d).$m[date("n",$d)].date(" (G:i)", $d);

	} else if ( $j == 6 ) {

		$dD = date("j ", $d).$m[date("n",$d)].date(" Y",$d)."r";

	} else if ( $j == 7 ) {

		$dD = $dTyg[date("w", $d)].", ".date("j ", $d).$m[date("n",$d)];

	} else if ( $j == 8 ) {

		$dD = $dTyg[date("w", $d)].", ".date("j ", $d).$m[date("n",$d)].date(" Y", $d);

	} else if ( $j == 9 ) {

		$dD = date("d",$d).".".date("m",$d)." ".date(" G:i",$d);

	} else if ( $j == 10 ) {

		$dD = date("j",$d)." ".$m[date("n",$d)]." ".date("Y",$d)." ".date(" G:i",$d);

	} else if ( $j == 0 ) {

		$dD = $m[date("n",$d)];
	}

	return $dD;

}


/** pobranie podkategorii
 *
 * name: getSubCat
 * @param: $cid
 * @return: subcategories
 */

function getSubCat( $cid ) {
	global $db;

	if ( $cid ) {

		$r = $db->select("SELECT * FROM "._pre_."category WHERE cat_sub_id = ".$cid." AND cat_show > 0");

		while( $row = $db->get_row($r,'MYSQL_ASSOC') ) {

			$tabela[] = $row;

		}

		if ($tabela) {

			$i=0;
			while($i<count($tabela)) {

				$wyniki[] = $tabela[$i];
				$cos = getSubCat($tabela[$i]['cat_id']);

				if ($cos) {

					$a=0;
					while($a<count($cos)) {

						$wyniki[] = $cos[$a];

						$a++;
					}

				}

				$i++;
			}

		}

		return $wyniki;

	}

	return null;

}


/** pobranie zdjęć z kategorii
 *
 * name: getPhotoSubCat
 * @param: $category
 * @return: $photos
 */

function getPhotoSubCat( $category ) {
	global $db;

	if ($category) {

		$i = 0;
		while($i<count($category)) {

			$r = $db->select("SELECT * FROM "._pre_."photo WHERE photo_cat_id = ".$category[$i]['cat_id']." AND photo_show > 0 ORDER BY photo_id DESC;");

			while( $row = $db->get_row($r,'MYSQL_ASSOC')) {

				$photo[] = $row;

			}

			$i++;
		}

		return $photo;

	}

	return null;

}


/** stronnicowanie
 *
 * name: pagination
 * @param: $array, $max, $page, $link, $js
 * @return: array ($results+$pages)
 */

function pagination ($array, $max=20, $page=1, $link="news.php?s=", $js=false, $next_txt=false, $prev_txt=false) {

if ( !$next_txt ) $next_txt = _("starsze wpisy");
if ( !$prev_txt ) $prev_txt = _("nowsze wpisy");
	if (!$page) $page = 1;

	$page_total = ceil(count($array)/$max);
	$page_pre_last = $page_total - 1;
	$first_page = 1;
	$next_page = '';
	$prev_page = '';

	if ($page_total > 1 ) {

		if ($page < $page_total) {

			$np = $page + 1;

			if (!$js) {

				$link_n = '<a href="'.$link.$np.'">';

			} else {

				$link_n = '<a href="#" onclick="'.$js.'('.$np.'); return false;">';

			}

			$next_page = '<div class="right">'.$link_n.$next_txt.'</a> &raquo;</div>';

		}

		if ($page > 1 ) {

			$pp = $page - 1;

			if (!$js) {

				$link_p = '<a href="'.$link.$pp.'">';

			} else {

				$link_p = '<a href="#" onclick="'.$js.'('.$pp.'); return false;">';

			}

			$prev_page = '<div class="left">&laquo; '.$link_p.$prev_txt.'</a></div>';

		}

		if ($page || $page > 1)
			$i=($page * $max) - $max;
		else
			$i = 0;

		$end_tag = $i+$max;

		if ($end_tag > count($array))
			$end_tag = count($array);

		while ($i<$end_tag) {

			$return[] = $array[$i];

			$i++;
		}

	} else {

		$i=0;
		while( $i<count($array)) {

			$return[] = $array[$i];

			$i++;
		}

		$next_page = false;
		$prev_page = false;
	}
	if ($next_page || $prev_page)
		$pagination = '<div class="pagination">'.$prev_page.$next_page.'<div class="clr"></div></div>';

	return array($return,$pagination);
}


/** link do komentarzy
 *
 * name: linkToComment
 * @param: $id, $cowhat, $txt
 * @return: link for comments
 */

function linkToComment( $id, $cowhat, $txt="") {
	global $db;

	$komentarzy_txt = _("komentarzy");

	if ( $cowhat == 1 ) {

		$idp = (int)$id;

		$r = $db->select("SELECT photo_file FROM "._pre_."photo WHERE photo_id = ".$idp);
		$foto = $db->get_row($r,'MYSQL_ASSOC');

		if ( $txt != 0 ) {

			$link = '<span class="comments"><a href="photo.php?idp='.$foto['photo_file'].'#comment-%COMMENTS_ID%" title="'.$komentarzy_txt.'%COMMENTS_SUM%">%COMMENTS_TXT%</a></span>';

		} else {

			$link = '<span class="comments"><a href="photo.php?idp='.$foto['photo_file'].'#comments" title="'.$komentarzy_txt.'%COMMENTS_SUM%">%COMMENTS_TXT%</a></span>';

		}

		$r = $db->select("SELECT COUNT(*) as ile, com_id FROM "._pre_."comments WHERE com_photo_id = ".$idp." AND com_show > 0 LIMIT 0,1;");
		$com = $db->get_row($r,'MYSQL_ASSOC');

		if (!isset($com['ile']))
			$com['ile'] = 0;
	}

	if ( $cowhat == 0 ) {

		$idn = (int)$id;

		if ( $txt != 0 ) {

			$link = '<span class="comments"><a href="news.php?id='.$idn.'#comment-%COMMENTS_ID%" title="'.$komentarzy_txt.'%COMMENTS_SUM%">%COMMENTS_TXT%</a></span>';

		} else {

			$link = '<span class="comments"><a href="news.php?id='.$idn.'#comments" title="'.$komentarzy_txt.'%COMMENTS_SUM%">%COMMENTS_TXT%</a></span>';

		}

		$r = $db->select("SELECT COUNT(*) as ile, com_id FROM "._pre_."comments WHERE com_news_id = ".$idn." AND com_show > 0 LIMIT 0,1;");
		$com = $db->get_row($r,'MYSQL_ASSOC');

		if (!isset($com['ile']))
			$com['ile'] = 0;

	}

	$link = str_replace('%COMMENTS_ID%', $com['com_id'], $link);
	$link = str_replace('%COMMENTS_SUM%', " ".$com['ile'], $link);
	$link = str_replace('%COMMENTS_TXT%', $txt.$com['ile'], $link);

	return $link;

}

/** tworzenie nagłówka
 * name:head
 * @param: none
 * return: $head
 */
function head() {
	global $conf;
$head = '<link rel="stylesheet" type="text/css" href="'.$conf['theme'].'css/style.css" />
<link rel="Shortcut Icon" type="image/png" href="'.$conf['url'].'icon.png" />
<meta name="generator" content="StudioGallery '.$conf['conf_version'].'" />
<meta name="robots" content="index,follow,all" />
<script type="text/javascript" src="'.$conf['url'].'libs/js/jquery/jquery-1.3.2.min.js"></script>';
if ( $conf['conf_jquery_lightbox'] == "1" ) {
$head .='
<script type="text/javascript" src="'.$conf['url'].'libs/js/jquery/jquery.lightbox.js"></script>
<script type="text/javascript" src="'.$conf['url'].'libs/js/jquery/jquery.lightbox.plugin.js"></script>';
}
if ( $conf['conf_jquery_lightbox'] == "2" ) {
$head .= '
<script type="text/javascript" src="'.$conf['url'].'libs/js/jquery/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="'.$conf['url'].'libs/js/jquery/jquery.fancybox-1.2.1.pack.js"></script>
<link rel="stylesheet" type="text/css" href="'.$conf['url'].'libs/js/jquery/css/jquery.fancybox.css" />
<script type="text/javascript" src="'.$conf['url'].'libs/js/fancy.js"></script>';
}
$head .= '
<script type="text/javascript" src="'.$conf['url'].'libs/js/jquery/jquery.loader-min.js"></script>
<script type="text/javascript" src="'.$conf['url'].'libs/js/jquery/jquery.infocontent-min.js"></script>
<script type="text/javascript" src="'.$conf['url'].'libs/js/jquery/jquery.rating-min.js"></script>
<link rel="stylesheet" type="text/css" href="'.$conf['theme'].'css/rating.css" />
<meta name="description" content="'.$conf['conf_desc'].'" />
<meta name="keywords" content="'.$conf['conf_keywords'].'" />
<link rel="canonical" href="'.$conf['conf_url'].'" />
<script type="text/javascript" src="'.$conf['url'].'libs/js/sg-min.js"></script>';

return $head;

}

function clear_theme_cache() {

	global $preU;
	foreach(glob($preU.'templates_c/**.php') as $file) {
		@unlink($file);
	}

}

/** tworzenie URLa z linku
 *
 * name: createURI
 * @param: $link
 * @return: $link
 */

function createURI ($link) {

	if ($link) {

		if (preg_match('/^(http:\/\/)/is',$link))
			return $link;
		else
			return 'http://'.$link;

	} else {

	return false;

	}

}


/** przygotowanie danych do zapisu
 *
 * name: dataToDb
 * @param: $text
 * @return: $safe_text
 */

function dataToDb($text) {
	$text = trim($text);
	$text = preg_replace('#<script(.*?)>(.*?)<\/script>#is','&lt;script$1&gt;$2&lt;/script&gt;',$text);
	preg_match_all('#<a(.*?)?href=\\\"(.*?)\\\">(.*?)</a>#is',$text,$matches);

	if (count($matches[0]) > 2 ) {

		$text = preg_replace('#<a(.*?)?href=\\\"(.*?)\\\">(.*?)</a>#is','$2',$text);

	}

	$text = htmlspecialchars(strip_tags($text,'<strong>,<em>,<u>,<a>'));
	$text = preg_replace("#\s+#"," ",$text);
	$text = preg_replace('#(\\\r)?(\\\n)#',"\n",$text);
	$text = trim($text);
	return $text;
}


/** przefiltrowanie danych pobranych z DB
 *
 * name: dataFromDb
 * @param: $text
 * @return: $text
 */

function dataFromDb($text) {

	return htmlspecialchars_decode(nl2br(stripslashes($text)));

}

function dataToEdit($text) {

	$text = preg_replace("#<br>#","\n",$text);
	$text = htmlspecialchars($text);
	return $text;

}

/** wysylanie maila
 * name: sendMail
 * @param: $temat, $tresc, $conf, $odkogo
 * @return: true - when send; false - when some false;
 */
function sendMail($temat,$tresc,$conf,$odkogo=false) {

	global $preU;
	require_once($preU."libs/class.phpmailer.php");
	$mail=new PHPMailer();
	$mail->PluginDir = $preU."libs/";
	if ( $conf['conf_smtp_host']) {

		$mail->IsSMTP();
		$mail->SMTPAuth   	= true;
		$mail->Host       	= $conf['conf_smtp_host'];
		$mail->Username   	= $conf['conf_email'];
		$mail->Password   	= $conf['conf_smtp_pass'];

	}

	$mail->SetLanguage("pl",$preU."libs/language/");
	$mail->CharSet 		= 'utf-8';
	$mail->From     	= $conf['conf_email'];
	$mail->FromName 	= $conf['conf_title'];
	$mail->Subject 		= strip_tags(trim($temat));
	$mail->Body 		= $tresc;
	$mail->AddAddress($conf['conf_email']);
	if (is_array($odkogo))
	$mail->AddReplyTo($odkogo['mail'],$odkogo['name']);

	if($mail->Send()) {

		$mail->ClearAddresses();
		$mail->ClearAttachments();
		return true;

	} else {

		$mail->ClearAddresses();
		$mail->ClearAttachments();
		echo $mail->ErrorInfo;
		return false;

	}

}

function addedComment($comwhat, $id, $comid) {

	global $db;
	global $conf;
	if ($comwhat == 1) {

		$r = $db->select("SELECT photo_title, photo_id, photo_file FROM "._pre_."photo WHERE photo_id = ".(int)$id.";");
		$c = $db->get_row($r,'MYSQL_ASSOC');

		$c['title'] = $c['photo_title'];
		if ( $conf['conf_comments'] < 2 )
			$c['link'] = $conf['conf_url'].'photo.php?idp='.$c['photo_file'].'#comment-'.(int)$comid;
		else
			$c['link'] = $conf['conf_url'].'sg-admin/comments.php';
	}
	if ($comwhat == 0) {
		$r = $db->select("SELECT news_title, news_id FROM "._pre_."blog WHERE news_id = ".(int)$id.";");
		$c = $db->get_row($r,'MYSQL_ASSOC');

		$c['title'] = $c['news_title'];
		if ( $conf['conf_comments'] < 2 )
			$c['link'] = $conf['conf_url'].'news.php?id='.$c['news_id'].'#comment-'.(int)$comid;
		else
			$c['link'] = $conf['conf_url'].'sg-admin/comments.php';
	}
	return $c;
}

function correct_link($link) {

	if ( !preg_match("#/$#",$link) )
	    $link = $link.'/';

	return $link;

}

function add_hook($where, $function) {

	global $sghook;
	$sghook->add_hook($where, $function);

}

function register_plugin($plugin_id, $data) {

	global $sghook;
	$sghook->register_plugin($plugin_id, $data);

}

function plugin_status($plugin_id,$data) {

    if ($plugin_id && $data) {
		global $db;
		$r = $db->select("SELECT * FROM "._pre_."plugins WHERE plugin_id_file LIKE '".$plugin_id."'");
		$row = $db->get_row($r,'MYSQL_ASSOC');
		if ($row) {
		    return $row['plugin_active'];
		} else {
	    	$dane = array(
			'plugin_id_file' => $plugin_id,
			'plugin_author' => $data['author'],
			'plugin_name' => $data['name'],
			'plugin_desc' => $data['desc'],
			'plugin_url' => $data['url'],
			'plugin_version'=> $data['version'],
			'plugin_options'=>$data['options']);
	    	$db->insert_array(_pre_."plugins",$dane);
	    	$r = $db->select("SELECT * FROM "._pre_."plugins WHERE plugin_id_file = ".$plugin_id);
	    	$row = $db->get_row($r,'MYSQL_ASSOC');
		}
		return $row['plugin_active'];
    } else {
    	return false;
    }
}

function list_all_plugins() {

	global $db;
	$r = $db->select("SELECT * FROM "._pre_."plugins ORDER BY plugin_active ASC, plugin_name DESC");
	$i=0; $a=0; $b=0;
	while($row = $db->get_row($r,'MYSQL_ASSOC')) {
	    if ($i%2 == 1) $col=2;
		else $col=1;
	    if ($a%2 == 1) $ca=2;
		else $ca=1;
	    if ($b%2 == 1) $cb=2;
		else $cb=1;
	    if ($row['plugin_url']) $author = '<a href="'.$row['plugin_url'].'">'.$row['plugin_author'].'</a>';
	    else $author = $row['plugin_author'];
	    if ($row['plugin_options']) $options = '<a href="plugins.php?options='.$row['plugin_id_file'].'" title="'._("edytuj ustawienia").'">'.$row['plugin_name'].'</a>';
	    else $options = $row['plugin_name'];
	    if ($row['plugin_active'] == 1) {
			$aktywne[] = '<div class="plugin active col-'.$col.' cactive-'.$ca.'"><div class="name">'.$options.'</div><div class="desc">'.$row['plugin_desc'].'</div><div class="author">'.$author.'</div><div class="version">'.$row['plugin_version'].'</div><div class="active"><a href="plugins.php?deactivate='.$row['plugin_id_file'].'">'._("wyłącz").'</a></div><div class="clr"></div></div>';
			$a++;
	    } else {
			$nieaktywne[] = '<div class="plugin deactive col-'.$col.' cdeactive-'.$cb.'"><div class="name">'.$row['plugin_name'].'</div><div class="desc">'.$row['plugin_desc'].'</div><div class="author">'.$author.'</div><div class="version">'.$row['plugin_version'].'</div><div class="active"><a href="plugins.php?activate='.$row['plugin_id_file'].'">'._("włącz").'</a></div><div class="clr"></div></div>';
	    	$b++;
	    }
		$i++;
	}
	return array($aktywne, $nieaktywne);
}

function cuterText($string, $end) {

	if( strlen($string)>$end ) {

		$string = clean($string);
		$string = preg_replace('/[\(\)\,\.\;\:\s]+?(\S+)?$/','',substr($string,0,$end+1));
		$string = substr($string,0,$end);
		$string .= "&nbsp;(...)&raquo;";
		// $string = preg_replace("/.*?\n$/", " ", $string);
	}
    return $string;
}

function clean($data) {

	$data = ereg_replace ("(\t)+", "\t", $data);
	$data = ereg_replace ("\r\n", "", $data);
	return ereg_replace (" +", " ", $data);

}
?>
